package com.cgsd.heyu.ui.info;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.android.library.adapter.BaseAdapter;
import com.android.library.adapter.ClickItemListener;
import com.android.library.adapter.ViewHolder;
import com.android.library.utils.BeanUtils;
import com.android.library.utils.LogUtils;
import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.common.CommonConfig;
import com.cgsd.heyu.common.UserModeConfig;
import com.cgsd.heyu.entity.PayEntity;
import com.cgsd.heyu.entity.PayResult;
import com.cgsd.heyu.entity.VipProductEntity;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManager;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.presenter.home.HomeContract;
import com.cgsd.heyu.presenter.home.HomePresenter;
import com.cgsd.heyu.ui.BaseActivity;
import com.cgsd.heyu.ui.task.vo.WxPayVo;
import com.cgsd.heyu.utils.ALiPayUtil;
import com.cgsd.heyu.utils.FormatUtil;
import com.cgsd.heyu.utils.StatusBarUtil;
import com.cgsd.heyu.utils.WXPayUtil;
import com.cgsd.heyu.widgets.dialog.ConfirmDialog;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.RequestBody;

/**
 * @author xiaoxing
 * Description 会员vip界面
 * CreateData: 2021/1/29
 */
public class VipActivity extends BaseActivity<HomeContract.Presenter> implements View.OnClickListener, HomeContract.VipView, ClickItemListener {
    public static final String PAY_SUCCESS = "9000";
    private ImageView mIvVip;
    private TextView mTvTitle;
    private TextView mTvDes;
    private LinearLayout mLayoutBuyExplain;
    private ImageView mIvSelectWeixin;
    private ImageView mIvSelectAlipay;
    private TextView tvTips;

    private BaseAdapter<VipProductEntity> adapter;
    private List<VipProductEntity> data = new ArrayList<>();
    private String payWay;
    private int currentPosition;
    private String aliPayStr;
    private ConfirmDialog confirmDialog;
    // 是否是第三方支付宝支付
    protected boolean isThirdAliPay = false;

    private Runnable payRunnable = new Runnable() {
        @Override
        public void run() {
            PayTask alipay = new PayTask(VipActivity.this);
            Map<String, String> result = alipay.payV2(aliPayStr, true);
            Message msg = new Message();
            msg.what = 100;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    private Handler mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            LogUtils.d("print", payResult.getResult());
            LogUtils.d("print", payResult.toString());
            com.apkfuns.logutils.LogUtils.e("payResult = " + payResult.toString());
            if (PAY_SUCCESS.equals(payResult.getResultStatus())) {
                //支付成功
                showPaySuccessDialog();
                mPresenter.getUserInfo();
            } else {
                //支付失败
                showToast("支付失败");
            }
            return false;
        }
    });
    private Context mContext;

    public static void actionStart(Activity activity) {
        Intent intent = new Intent(activity, VipActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_vip;
    }

    @Override
    protected void initView() {
        new HomePresenter(this);
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        mContext = this;
        mIvVip = findViewById(R.id.iv_vip);
        mTvTitle = findViewById(R.id.tv_vip_title);
        mTvDes = findViewById(R.id.tv_des);
        tvTips = findViewById(R.id.tv_tips);
        mLayoutBuyExplain = findViewById(R.id.layout_buy_explain);
        mIvSelectWeixin = findViewById(R.id.iv_select_weixin);
        mIvSelectAlipay = findViewById(R.id.iv_select_alipay);
        RecyclerView mRecyclerView = findViewById(R.id.mRecyclerView);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new BaseAdapter<VipProductEntity>(this, R.layout.item_vip_product, data) {
            @SuppressLint("SetTextI18n")
            @Override
            public void convert(ViewHolder holder, VipProductEntity entity, int position) {
                RelativeLayout layoutRoot = holder.getView(R.id.root);
                TextView tvRecommend = holder.getView(R.id.tv_recommend);
                TextView tvPrice = holder.getView(R.id.tv_price);
                TextView tvConfusePrice = holder.getView(R.id.tv_confuse_price);

                tvConfusePrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); // 中划线
                tvConfusePrice.setText("¥" + FormatUtil.getPrice(entity.getMarkingPrice()));
                tvPrice.setText("¥" + FormatUtil.getPrice(entity.getRealPrice()));
                holder.setText(R.id.tv_title, entity.getVipName());

                if (currentPosition == position) {
                    layoutRoot.setBackgroundResource(R.drawable.border_blue_solid_blue);
                } else {
                    layoutRoot.setBackgroundResource(R.drawable.border_gray_solid_white);
                }
                if (position == 0) {
                    tvRecommend.setVisibility(View.VISIBLE);
                } else {
                    tvRecommend.setVisibility(View.GONE);
                }
            }
        };
        mRecyclerView.setAdapter(adapter);
        adapter.setClickItemListener(this);
        findViewById(R.id.layout_alipay).setOnClickListener(this);
        findViewById(R.id.layout_weixin).setOnClickListener(this);
        findViewById(R.id.tv_submit).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        tvTips.setText(getString(R.string.vip_buy_explain_tips, CommonConfig.getInstance().weixinNo));
        setSelectPayWay(VipProductEntity.PAY_ALIPAY);
        mPresenter.getUserInfo();
        mPresenter.vipProduct();
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.fullBar(this);
    }

    /**
     * 选择付款方式
     */
    private void setSelectPayWay(String type) {
        payWay = type;
        if (VipProductEntity.PAY_ALIPAY.equals(payWay)) {
            mIvSelectAlipay.setSelected(true);
            mIvSelectWeixin.setSelected(false);
        } else {
            mIvSelectAlipay.setSelected(false);
            mIvSelectWeixin.setSelected(true);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.layout_alipay) {
            setSelectPayWay(VipProductEntity.PAY_ALIPAY);
        } else if (v.getId() == R.id.layout_weixin) {
            setSelectPayWay(VipProductEntity.PAY_WEIXIN);
        } else if (v.getId() == R.id.tv_submit) {
            submitData();
        }
    }


    @Override
    public void vipProduct(List<VipProductEntity> entities) {
        if (BeanUtils.isEmpty(entities)) {
            return;
        }

        data.clear();
        data.addAll(entities);
        adapter.notifyDataSetChanged();

        List<VipProductEntity.Payment> payment = entities.get(0).getPayment();
        for (int i = 0; i < payment.size(); i++) {
            VipProductEntity.Payment payment1 = payment.get(i);
            String type = payment1.getType();
            if ("adapay".equals(type)) {
                isThirdAliPay = true;
                break;
            }
        }
    }

    @Override
    public void setAlipayData(PayEntity payEntity) {
        dismissCommonSubmitDialog();
        if (payEntity == null) {
            return;
        }
        aliPayStr = payEntity.getBody();
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setUserInfo(UserModeConfig userInfo) {
        if (userInfo == null) {
            return;
        }
        if (userInfo.vipLevel > 0) {
            mTvTitle.setText(getString(R.string.vip_title_tips3));
            mTvDes.setText(getString(R.string.vip_title_tips4));
        } else {
            mTvTitle.setText(getString(R.string.vip_title_tips1));
            mTvDes.setText(getString(R.string.vip_title_tips2));
        }
    }

    @Override
    public void clickItem(View view, int position) {
        if (position != currentPosition) {
            currentPosition = position;
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 提现提交数据
     */
    private void submitData() {
        if (BeanUtils.isEmpty(data)) {
            showToast("数据错误");
            return;
        }
        showCommonSubmitDialog("");
        if (VipProductEntity.PAY_ALIPAY.equals(payWay)) {
            // TODO: 2021/4/8   原生 第三方切换
//            mPresenter.alipay(data.get(currentPosition).getSeqId());
//            mPresenter.thirdAlipay(data.get(currentPosition).getSeqId());
            if (!ALiPayUtil.isAliPayInstalled(this)) {
                showToast("请先安装支付宝");
                dismissCommonSubmitDialog();
                return;
            }
            if (isThirdAliPay) {
                alipayInfo(data.get(currentPosition).getSeqId());
            } else {
                mPresenter.alipay(data.get(currentPosition).getSeqId());
            }
        } else {
            wechatPay(data.get(currentPosition).getSeqId());
        }
    }


    /**
     * 支付成功
     */
    private void showPaySuccessDialog() {
        if (confirmDialog == null) {
            confirmDialog = new ConfirmDialog(this);
            confirmDialog.setTitle("支付成功，如果数据没刷新，请退出重新进入");
            confirmDialog.setDialogListener(new ConfirmDialog.DialogListener() {
                @Override
                public void confirm() {
                    confirmDialog.dismiss();
                }

                @Override
                public void cancel() {
                    confirmDialog.dismiss();
                }
            });
        }
        confirmDialog.show();
    }

    /**
     * 支付宝支付
     *
     * @param orderNo
     */
    private void alipayInfo(String orderNo) {
        HashMap<String, Object> data = new HashMap<>();
        data.put("orderNo", orderNo);
        com.apkfuns.logutils.LogUtils.e("orderNo " + orderNo);
        RequestBody requestBody = RetrofitServiceManager.getBody(data);
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .aliPay(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<PayEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<PayEntity> baseResponse) {
//                        processWechatData(baseResponse.getBizBody());
                        dismissCommonSubmitDialog();

                        com.apkfuns.logutils.LogUtils.e("onSuccess " + baseResponse.getBizBody());
                        if (baseResponse.getBizBody().getBody() == null) {
                            showToast("支付失败");
                            return;
                        }
                        mPresenter.thirdAlipay(baseResponse.getBizBody().getBody(), mContext);
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        com.apkfuns.logutils.LogUtils.e("onError = " + error.getMessage());
                        setErrorMessage(error);
                    }
                });
    }

    /**
     * 微信支付
     *
     * @param orderNo
     */
    public void wechatPay(String orderNo) {
        HashMap<String, Object> data = new HashMap<>();
        data.put("orderNo", orderNo);
        RequestBody requestBody = RetrofitServiceManager.getBody(data);
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .wechatPay(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<PayEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<PayEntity> baseResponse) {
                        processWechatData(baseResponse.getBizBody());
                        dismissCommonSubmitDialog();
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        setErrorMessage(error);
                    }
                });
    }

    /**
     * process wechat data
     *
     * @param payEntity
     */
    public void processWechatData(PayEntity payEntity) {
        dismissCommonSubmitDialog();
        if (payEntity == null) {
            return;
        }
        try {
            String replace = payEntity.getBody().replace("package", "packageX");
            WxPayVo wxPayVo = new Gson().fromJson(replace, WxPayVo.class);
            new WXPayUtil(this, wxPayVo, "orderPay");
        } catch (JsonSyntaxException e) {
            showToast(getString(R.string.a_config_error_tip));
        }
    }
}
